/*
 * Copyright (C) 2012 deathowl
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package rpg.console;

import java.awt.event.KeyEvent;
import java.util.LinkedList;
import java.util.List;
import rpg.RPG;
import rpg.gfx.Bitmap;
import rpg.gfx.OverlayEffect;

/**
 *
 * @author deathowl
 */
public class Console extends OverlayEffect {

    private int color = 0xcc000000;
    private boolean opened = false;
    private static Console instance;
    private String actualLine = "";
    private List<Bitmap> lines = new LinkedList<Bitmap>();

    public Console(int width, int height) {
        super(width, height, 0, 0);
        clearWith(color);
        for(int i = 0; i<20; i++){
            lines.add(new Bitmap(1,1));
        }
    }

    @Override
    public boolean tick() {
        if (opened) {
            if (!actualLine.equals("")) {
                if (RPG.keylistener.isKeyDown2(KeyEvent.VK_ENTER) && !actualLine.isEmpty()) {
                    runLine(actualLine);
                    RPG.keylistener.clearCache();
                    System.out.println(actualLine);
                    actualLine = "";
                }
            }
            actualLine += RPG.keylistener.getAndClearCache();
        }
        return true;
    }

    public static void newInstance(int width, int height) {
        instance = new Console(width, height);
    }

    public static Console getInstance() {
        if (instance == null) {
            newInstance(RPG.WINDOW_WIDTH - 20, RPG.WINDOW_HEIGHT - 20);

        }
        return instance;
    }

    public boolean isVisible() {
        return opened;
    }

    public void setActualLine(String actualLine) {
        this.actualLine = actualLine;
    }

    public void open() {
        this.opened = true;
    }

    public void close() {
        this.opened = false;
    }

    public void toggle() {
        opened = !opened;
    }

    public void runLine(String line) {
        printLine(line);
        CommandParser cn=CommandParser.getInstance();
        cn.tryRun(line);
    }
    public void printLine(String line){
       lines.add(RPG.fs.getText(line, (byte) 2, 0xffffffff));
        if (lines.size() > 20) {
            lines.remove(0);
        }
        int i = 0;
        clearWith(color);
        for (Bitmap b : lines) {
            draw(b, 6, 6 + i * 21);
            i++;
        }
    }
}
